use axum::{
    extract::{Json, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};
use sqlx::MySqlPool;
use crate::models::{Store, StoreCreateRequest, StoreDeleteRequest};

pub async fn getall(
    State(pool): State<MySqlPool>
) -> Response {
    match sqlx::query_as::<_, Store>(
        "SELECT * FROM store_information"
    )
    .fetch_all(&pool)
    .await {
        Ok(results) => {
            (StatusCode::OK, Json(results)).into_response()
        },
        Err(e) => {
            println!("存货记录数据库查询错误：{:?}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({
                    "error": "存货记录数据库查询失败！"
                }))
            ).into_response()
        }
    }
}

pub async fn create(
    State(pool): State<MySqlPool>,
    Json(create_req): Json<StoreCreateRequest>,
) -> Response {
    // 如果商品不存在，则创建新商品
    match sqlx::query(
        r#"
        INSERT INTO store_information (name, amount, price, date)
        VALUES (?, ?, ?, ?)
        "#
    )
    .bind(&create_req.name)
    .bind(&create_req.amount)
    .bind(&create_req.price)
    .bind(&create_req.date)
    .execute(&pool)
    .await {
        Ok(_) => {
            (StatusCode::OK, Json(serde_json::json!({
                "message": "存货记录创建成功"
            }))).into_response()
        },
        Err(e) => {
            println!("存货记录数据库插入错误：{:?}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({
                    "error": "存货记录创建失败"
                }))
            ).into_response()
        }
    }
}

pub async fn delete(
    State(pool): State<MySqlPool>,
    Json(delete_req): Json<StoreDeleteRequest>,
) -> Response {
    // 如果商品不存在，则创建新商品
    match sqlx::query(
    "DELETE FROM store_information WHERE id = ?"
    )
    .bind(&delete_req.id)
    .execute(&pool)
    .await {
        Ok(_) => {
            (StatusCode::OK, Json(serde_json::json!({
                "message": "存货记录删除成功"
            }))).into_response()
        },
        Err(e) => {
            println!("存货记录数据库删除错误：{:?}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({
                    "error": "存货记录删除失败"
                }))
            ).into_response()
        }
    }
}